//
//  ADMapView.m
//  Anda_Driver_Pro
//
//  Created by AnDa-Y on 2019/8/5.
//  Copyright © 2019 AnDa-Y. All rights reserved.
//

#import "ADMapView.h"
#import "MANaviRoute.h"
#import <MAMapKit/MAMapKit.h>

#import "CommonUtility.h"
#import "ErrorInfoUtility.h"
#import "MAAnnotationView+Category.h"

static NSString * const kMapRouteStartTitle = @"起点";
static NSString * const kMapRouteEndTitle = @"终点";
static NSString * const kMapRouteDriverTitle = @"司机";
static NSInteger const kMapRouteMinEdge = 20;

@interface ADMapView ()<MAMapViewDelegate>

@property(nonatomic , strong) MANaviRoute *naviRoute;
@property(nonatomic , strong) MAAnnotationView *driverLocation;
@property(nonatomic , strong) MAMapView *realMapView;

@end

@implementation ADMapView

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        [self initMapView];
    }
    return self;
}

- (void)awakeFromNib
{
    [super awakeFromNib];
    [self initMapView];
}

- (void)initMapView {
    
    self.realMapView = [[MAMapView alloc] init];
    self.realMapView.userLocationAccuracyCircle.radius = 0;
    self.realMapView.zoomLevel = 12;
    self.realMapView.showsUserLocation = YES;
    self.realMapView.delegate = self;
    [self addSubview:self.realMapView];
    
    self.realMapView.translatesAutoresizingMaskIntoConstraints = NO;
    NSLayoutConstraint *left = [self.realMapView.leftAnchor constraintEqualToAnchor:self.leftAnchor];
    NSLayoutConstraint *rignt = [self.realMapView.rightAnchor constraintEqualToAnchor:self.rightAnchor];
    NSLayoutConstraint *top = [self.realMapView.topAnchor constraintEqualToAnchor:self.topAnchor];
    NSLayoutConstraint *bottom = [self.realMapView.bottomAnchor constraintEqualToAnchor:self.bottomAnchor];
    [NSLayoutConstraint activateConstraints:@[left, rignt, top, bottom]];
}

- (void)adjustShowCurrentLocation
{
    self.realMapView.centerCoordinate = self.realMapView.userLocation.coordinate;
}

- (void)adjustShowTrafficLayer
{
    self.realMapView.showTraffic = !self.realMapView.showTraffic;
}

- (void)setMapRoutePlanEdgeInsets:(UIEdgeInsets)mapEdgeInsets
{
    self.mapEdgeInsets = mapEdgeInsets;
}

- (void)addAnnotationWithCoordinate:(CLLocationCoordinate2D)coor title:(NSString *)title
{
    if (CLLocationCoordinate2DIsValid(coor) && title.length) {
        MAPointAnnotation *annotation = [[MAPointAnnotation alloc] init];
        annotation.coordinate = coor;
        annotation.title = title;
        [self.realMapView addAnnotation:annotation];
    }
}

- (void)removeAllAnnotations
{
    [self.realMapView removeAnnotations:self.realMapView.annotations];
}

- (void)showRoute:(id)route aCoordinate:(CLLocationCoordinate2D)aCoor bCoordinate:(CLLocationCoordinate2D)bCoor
{
    [self removeAllRoutes];
    
    AMapGeoPoint *startPoint = [AMapGeoPoint locationWithLatitude:aCoor.latitude longitude:aCoor.longitude];
    AMapGeoPoint *endPoint = [AMapGeoPoint locationWithLatitude:bCoor.latitude longitude:bCoor.longitude];
    
    self.naviRoute = [MANaviRoute naviRouteForPath:(AMapPath *)route withNaviType:MANaviAnnotationTypeDrive showTraffic:NO startPoint:startPoint endPoint:endPoint];
    self.naviRoute.routeColor = [UIColor blueColor];
    [self.naviRoute addToMapView:self.realMapView]; // 将路线添加到地图
    
    MAMapRect mapRect = [CommonUtility mapRectForOverlays:self.naviRoute.routePolylines];
    [self.realMapView setVisibleMapRect:mapRect edgePadding:self.mapEdgeInsets animated:YES];
}

//移除路径
- (void)removeAllRoutes
{
    [self.naviRoute removeFromMapView];
}

- (void)removeAllLayers
{
    [self removeAllAnnotations];
    [self removeAllRoutes];
}

#pragma 代理方法
- (void)mapInitComplete:(MAMapView *)mapView
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.realMapView.centerCoordinate = self.realMapView.userLocation.coordinate;
    });
}

#pragma mark - MAMapViewDelegate
- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id<MAOverlay>)overlay
{
    if ([overlay isKindOfClass:[LineDashPolyline class]]){
        MAPolylineRenderer *plRenderer = [[MAPolylineRenderer alloc] initWithPolyline:((LineDashPolyline *)overlay).polyline];
        plRenderer.lineWidth   = 8;
        plRenderer.lineDash = YES;
        plRenderer.lineCapType = kMALineCapRound;
        plRenderer.lineJoinType = kMALineJoinRound;
        plRenderer.strokeColor = [UIColor blueColor];
        
        return plRenderer;
    }
    
    if ([overlay isKindOfClass:[MANaviPolyline class]]){
        MANaviPolyline *naviPolyline = (MANaviPolyline *)overlay;
        MAPolylineRenderer *plRenderer = [[MAPolylineRenderer alloc] initWithPolyline:naviPolyline.polyline];
        
        plRenderer.lineWidth = 8;
        plRenderer.lineCapType = kMALineCapRound;
        plRenderer.lineJoinType = kMALineJoinRound;
        if (naviPolyline.type == MANaviAnnotationTypeWalking){
            plRenderer.strokeColor = self.naviRoute.walkingColor;
        }else if (naviPolyline.type == MANaviAnnotationTypeRailway){
            plRenderer.strokeColor = self.naviRoute.railwayColor;
        }else{
            plRenderer.strokeColor = self.naviRoute.routeColor;
        }
        return plRenderer;
    }
    if ([overlay isKindOfClass:[MAMultiPolyline class]]){
        MAMultiColoredPolylineRenderer * plRenderer = [[MAMultiColoredPolylineRenderer alloc] initWithMultiPolyline:overlay];
        
        plRenderer.lineWidth = 10;
        plRenderer.strokeColors = [self.naviRoute.multiPolylineColors copy];
        plRenderer.gradient = YES;
        plRenderer.lineCapType = kMALineCapRound;
        plRenderer.lineJoinType = kMALineJoinRound;
        return plRenderer;
    }
    
    //导航线路
    if ([overlay isKindOfClass:[MAPolyline class]]){
        
        MAPolylineRenderer *plRenderer = [[MAPolylineRenderer alloc] initWithPolyline:overlay];
        plRenderer.lineWidth = 8;
        plRenderer.lineCapType = kMALineCapRound;
        plRenderer.lineJoinType = kMALineJoinRound;
        plRenderer.strokeColor = [UIColor blueColor];
        
        return plRenderer;
    }
    
    return nil;
}

// 控制车头转换
- (void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation {
    [self.driverLocation rotateWithHeading:userLocation.heading];
}

- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
    if ([annotation isKindOfClass:[MAUserLocation class]]){

        MAAnnotationView *driverLocation = [mapView dequeueReusableAnnotationViewWithIdentifier:kMapRouteDriverTitle];
        if (!driverLocation) {
            driverLocation = [[MAAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:kMapRouteDriverTitle];
        }

        driverLocation.image = [UIImage imageNamed:@"icon_car_a"];
        driverLocation.imageView.frame = CGRectMake(0, 0, 57, 57);
        driverLocation.zIndex = 10;
        self.driverLocation = driverLocation;
        return driverLocation;
    }
    
    if ([annotation isKindOfClass:[MAPointAnnotation class]]){
        static NSString *routePlanningCellIdentifier = @"RoutePlanningCellIdentifier";
        
        MAAnnotationView *poiAnnotationView = (MAAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:routePlanningCellIdentifier];
        if (poiAnnotationView == nil){
            poiAnnotationView = [[MAAnnotationView alloc] initWithAnnotation:annotation
                                                             reuseIdentifier:routePlanningCellIdentifier];
        }
        
        poiAnnotationView.canShowCallout = YES;
        
        if ([annotation isKindOfClass:[MANaviAnnotation class]]){
            
            switch (((MANaviAnnotation*)annotation).type){
                    
                case MANaviAnnotationTypeRailway:
                    poiAnnotationView.image = [UIImage imageNamed:@"railway_station"];
                    break;
                    
                case MANaviAnnotationTypeBus:
                    poiAnnotationView.image = [UIImage imageNamed:@"bus"];
                    break;
                    
                case MANaviAnnotationTypeDrive:
                    
                    if ([poiAnnotationView.annotation.title isEqualToString:@"起点"]) {
                        
                        poiAnnotationView.image = [UIImage imageNamed:@"map_icon_start"];
                        
                    }else if ([poiAnnotationView.annotation.title isEqualToString:@"终点"]) {
                        
                        poiAnnotationView.image = [UIImage imageNamed:@"map_icon_end"];
                        
                    }else if([poiAnnotationView.annotation.title isEqualToString:@"乘客"]){
                        
                        poiAnnotationView.image = [UIImage imageNamed:@"map_icon_start"];
                        
                    }else{
                        
                    }
                    
                    break;
                    
                case MANaviAnnotationTypeWalking:
                    poiAnnotationView.image = [UIImage imageNamed:@"man"];
                    break;
                    
                default:
                    break;
            }
            
        }else{
            
            if ([[annotation title] isEqualToString:kMapRouteStartTitle]){
                poiAnnotationView.image = [UIImage imageNamed:@"map_icon_start"];
            }else if([[annotation title] isEqualToString:kMapRouteEndTitle]){
                poiAnnotationView.image = [UIImage imageNamed:@"map_icon_end"];
            }else if([poiAnnotationView.annotation.title isEqualToString:@"乘客"]){
                poiAnnotationView.image = [UIImage imageNamed:@"map_icon_start"];
            }else{
                
            }
        }
        
        return poiAnnotationView;
    }
    
    return nil;
}

- (void)mapView:(MAMapView *)mapView didAddAnnotationViews:(NSArray *)views{
    MAAnnotationView *view = views[0];
    // 放到该方法中用以保证userlocation的annotationView已经添加到地图上了。
    if ([view.annotation isKindOfClass:[MAUserLocation class]]){
        MAUserLocationRepresentation *r = [[MAUserLocationRepresentation alloc] init];
        r.showsAccuracyRing = false;///精度圈是否显示，默认YES
        [mapView updateUserLocationRepresentation:r];
    }
}

@end
